package com.yang.tools.httpdownloader;

import java.util.ArrayList;
import java.util.List;

import com.yang.tools.util.PathUtil;

public class HtmlParser
{
	private final String CONTENT_START_TAG = "Parent Directory</a>";
	private final String LINK_START = "<a href=";
	private final String LINK_END = ">";
	private final String QUOTA = "\"";
	private final String FOLDER_SUFFIX_TAG = "/";

	private List<String> fileLinks = new ArrayList<String>();
	private List<String> folderLinks = new ArrayList<String>();

	// private final String[] FILE_SUFFIX_TAG = new String[] { ".tar", ".gz",
	// ".zip", ".jar", ".html", ".htm", ".jsp", ".cfg", ".properties",
	// ".xml", ".js", ".doc",".pdf" };

	public HtmlParser findLinks(String ulr, String htmlcontent)
	{
		ulr = PathUtil.completeTheTailSlash(ulr);
		StringBuilder sb = new StringBuilder(htmlcontent.substring(htmlcontent
				.indexOf(CONTENT_START_TAG)+CONTENT_START_TAG.length()));
		htmlcontent = null;
		int index = 0;
		String link = "";

		while ((index = sb.indexOf(LINK_START)) > 0)
		{
			sb = sb.delete(0, index + LINK_START.length());
			link = sb.substring(0, sb.indexOf(LINK_END));
			link = link.trim().replace("\"", "");
			if (!link.endsWith(FOLDER_SUFFIX_TAG))
			{
				fileLinks.add(ulr + link);
			}
			else
			{
				folderLinks.add(ulr + "/" + link);
			}
		}
		return this;
	}

	public HtmlParser findLinksWithDirectPath(String htmlcontent)
	{
		StringBuilder sb = new StringBuilder(htmlcontent.substring(htmlcontent
				.indexOf(CONTENT_START_TAG)));
		htmlcontent = null;
		int index = 0;
		String link = "";

		while ((index = sb.indexOf(LINK_START)) > 0)
		{
			sb = sb.delete(0, index + LINK_START.length());
			link = sb.substring(0, sb.indexOf(LINK_END));
			link = link.trim().replace("\"", "");
			if (!link.endsWith(FOLDER_SUFFIX_TAG))
			{
				fileLinks.add(link);
			}
			else
			{
				folderLinks.add(link);
			}
		}
		return this;
	}

	public List<String> getFileLinks()
	{
		return fileLinks;
	}

	public List<String> getFolderLinks()
	{
		return folderLinks;
	}

}
